//
//  CHHomeViewController.m
//  CarFile
//
//  Created by 陈浩 on 2017/3/20.
//  Copyright © 2017年 陈浩. All rights reserved.
//

#import "CHHomeViewController.h"
#import "CHQueryViewController.h"
#import "CHScrollView.h"
#import "CHRollView.h"
#import "CHHomeViewCell.h"
#import "CHPopView.h"
#import "CHEvaluationListController.h"
#import "CHComplainCountController.h"
#import "CHAccountViewController.h"
#import "CHInformViewController.h"
#import "CHInformDetailController.h"
#import "CHExceptionListController.h"
#import "CHReviewedController.h"
#import "CHYYGLViewController.h"
#import "SelectAlert.h"
#import "PJ_Model.h"
#import "CHNoticeModel.h"
#import "JXButton.h"
#define UIScreenW  [UIScreen mainScreen].bounds.size.width
typedef void(^RequestCompelete)(id result);
@interface CHHomeViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,CHPopViewDelegate>

@property (nonatomic ,copy) NSString *startTime;
@property (nonatomic ,copy) NSString *endTime;
@property (nonatomic ,copy) NSString *remarksPath;
@property (nonatomic ,strong) NSMutableArray *datas;
@property (nonatomic ,strong) UIView *bgView;
@property (nonatomic ,strong) CHScrollView *scrollView;
@property (nonatomic ,strong) UIView *headerView;
@property (nonatomic ,strong) CHRollView *rollView;
@property (nonatomic ,strong) UICollectionView *collectionView;
@property (nonatomic ,strong) UIView *mainView;
@property (nonatomic ,strong) CHPopView *popView;
@property (nonatomic ,strong) NSArray *titles;
@property (nonatomic ,strong) NSArray *resultArr;
@property (nonatomic ,strong) UIButton *selectBtn;
@property (nonatomic ,strong) UILabel *signLabel;
@property (nonatomic ,strong) UIView *menuView;
@property (nonatomic ,strong) NSArray *noticeTitles;
@property (nonatomic ,strong) NSMutableArray *noticeArr;
@property (nonatomic ,strong) UIAlertView *alertView;
@property (nonatomic ,strong) dispatch_semaphore_t  semaphore;

@end

@implementation CHHomeViewController
-(NSMutableArray *)noticeArr{
    if (!_noticeArr) {
        _noticeArr = [NSMutableArray array];
    }
    return _noticeArr;
}


-(NSMutableArray *)datas{
    
    if (!_datas) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}


-(NSArray *)resultDic{
    
    if (!_resultArr) {
        _resultArr = [NSArray array];
    }
    return _resultArr;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = KRGB(230, 243, 252);
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    self.titles = @[@"维修车辆",@"维修记录",@"已注册企业",@"配件使用数",@"评价",@"投诉"];
    
    self.startTime =[Util getStartTimeWithNumber:7];
    self.endTime = [Util getCurrentTime];
    
    
    BOOL isLogin = [Util boolForkey:@"islogin"];
//    NSString *serviceURL = (NSString *)[Util getValue:@"serviceURL"];
    if (isLogin ) {
        //    检查是否需要更新版本
        [self checkVersion];
    }
    
    [self setupLeftBarButtonItem];
    
    [self setupHeaderView];
    
    //  创建通知信息滚动视图
    [self setupRollView];
    
    //  创建查询菜单主体
    [self setupMainView];
    
    //   请求网络数据
    [self getNetworkingData];
    
}

-(void)setupHeaderView{
    
//    头部背景图片
    UIImageView *headerBgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, UIScreenW, 234*ScaleY)];
    headerBgView.userInteractionEnabled = YES;
    headerBgView.image = [UIImage imageNamed:@"banner"];
    [self.view insertSubview:headerBgView atIndex:0];
    self.headerView = headerBgView;
    
//    用户信息按钮
    UIButton *userBtn = [[UIButton alloc] initWithFrame:CGRectMake(12, 24, 21, 21)];
    [userBtn setImage:[UIImage imageNamed:@"user"] forState:UIControlStateNormal];
    [userBtn addTarget:self action:@selector(leftBarButtonItemClick) forControlEvents:UIControlEventTouchUpInside];
    [headerBgView addSubview:userBtn];
    
//    省份
    UILabel *areacnLabel = [[UILabel alloc] initWithFrame:CGRectMake(UIScreenW - 100, 22, 90, 30)];
    areacnLabel.font = Font(14);
    areacnLabel.text = [Globle getInstance].userInfoDic[@"areacn"];
    areacnLabel.textColor = [UIColor whiteColor];
    areacnLabel.textAlignment = NSTextAlignmentCenter;
    [headerBgView addSubview:areacnLabel];
    
    
    UIView *menuView = [[UIView alloc] initWithFrame:CGRectMake(12, 165*ScaleY, UIScreenW - 2 *12, 90*ScaleY)];
    menuView.backgroundColor = [UIColor whiteColor];
    menuView.layer.cornerRadius = 5;
    menuView.layer.masksToBounds = YES;
    menuView.layer.borderWidth = 0.5;
    menuView.layer.borderColor = [UIColor colorWithHexString:@"098edd" alpha:0.2f].CGColor;
    [self.view insertSubview:menuView atIndex:1];
    self.menuView = menuView;
    
    CGFloat marginW = (menuView.w - 4 *50*ScaleX)/5;
    NSArray *titleArr = @[@"待审核",@"维修企业",@"异常企业",@"预约管理"];
    for (int i = 0; i< 4; i++) {
        JXButton *btn = [[JXButton alloc] initWithFrame:CGRectMake(marginW + i * (marginW + 50*ScaleX), 15*ScaleY, 50*ScaleX, 60*ScaleY)];
        btn.tag = i;
        [btn setTitle:[NSString stringWithFormat:@"%@",titleArr[i]] forState:0];
        [btn setTitleColor:[UIColor blackColor] forState:0];
        btn.titleLabel.font = Font(12);
        NSString *imgName = [NSString stringWithFormat:@"home_menu_%d",i+1];
        [btn setImage:[UIImage imageNamed:imgName] forState:0];
        [btn addTarget:self action:@selector(menuBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [menuView addSubview:btn];
    }
    
}


-(void)menuBtnClick:(JXButton *)btn{
    if (btn.tag == 0) {
       
        self.tabBarController.selectedIndex = 2;
        
    }else if (btn.tag == 1){
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeToWXQY" object:nil];
        UINavigationController *nav = [self.tabBarController.viewControllers objectAtIndex:3];
        UIViewController *vc = nav.topViewController;
        
        if ([vc isKindOfClass:[CHQueryViewController class]]) {
            [((CHQueryViewController *)vc) setMark:1];
        }
        self.tabBarController.selectedIndex = 3;
        
        
    }else if (btn.tag == 2){
        CHExceptionListController *vc = [[CHExceptionListController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if (btn.tag == 3) {
        CHYYGLViewController *vc = [[CHYYGLViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}



-(void)setupLeftBarButtonItem{
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 21, 21)];
    [btn setImage:[UIImage imageNamed:@"user"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(leftBarButtonItemClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    
    
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
    label.font = [UIFont systemFontOfSize:14];
    label.text = [Globle getInstance].userInfoDic[@"areacn"];
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:label];
    
}


#pragma mark - 搭建UI界面

-(void)setupMainView{
    
    UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.bgView.frame) + 8, UIScreenW, UIScreenH - CGRectGetMaxY(self.bgView.frame) - 8 )];
    mainView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:mainView];
    self.mainView = mainView;
    
    
    UIView *signView = [[UIView alloc] initWithFrame:CGRectMake(12, 13*ScaleY, 2, 18*ScaleY)];
    signView.backgroundColor = KRGB(9, 142, 221);
    [mainView addSubview:signView];
    
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(signView.frame)+5, 0, UIScreenW/2, 44*ScaleY)];
    titleLabel.textColor = KRGB(9,142, 221);
    titleLabel.text = @"最近一周统计";
    titleLabel.font =Font(16);
    [mainView addSubview:titleLabel];
    self.signLabel = titleLabel;
    
    
    UIButton *moreBtn = [[UIButton alloc] initWithFrame:CGRectMake(UIScreenW - 44-10, 0, 44, 44*ScaleY)];
    moreBtn.titleLabel.font = Font(14);
    [moreBtn setTitle:@"更多" forState:UIControlStateNormal];
    [moreBtn setTitleColor:[UIColor colorWithHexString:@"666666" alpha:1.0f] forState:UIControlStateNormal];
    [moreBtn addTarget:self action:@selector(selectBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [mainView addSubview:moreBtn];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(titleLabel.frame), UIScreenW, 1)];
    line.backgroundColor = [UIColor colorWithHexString:@"f3f3f3" alpha:1.0f];
    [mainView addSubview:line];
    
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 1;
    flowLayout.itemSize = CGSizeMake(UIScreenW /2, 90 *ScaleY);
    UICollectionView *collectionView =  [[UICollectionView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(line.frame), UIScreenW, mainView.frame.size.height - CGRectGetMaxY(line.frame) - 49 ) collectionViewLayout:flowLayout];
    collectionView.backgroundColor = [UIColor colorWithHexString:@"eeeef0" alpha:1.0];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.scrollEnabled = YES;
    collectionView.showsHorizontalScrollIndicator = NO;
    [collectionView registerClass:[CHHomeViewCell class] forCellWithReuseIdentifier:@"homeCell"];
    [mainView addSubview:collectionView];
    self.collectionView = collectionView;
    
    
}



-(void)setupRollView{
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.menuView.frame) +10, UIScreenW , 44*ScaleY)];
    bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgView];
    self.bgView = bgView;
    
    UIImageView *noticeImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"notice"]];
    noticeImg.frame = CGRectMake(10, 14.5, 70*ScaleX, 15*ScaleY);
    [bgView addSubview:noticeImg];
    
    //分割线
    CALayer *line = [CALayer layer];
    line.backgroundColor = [UIColor colorWithHexString:@"ececec" alpha:1.0].CGColor;
    line.frame = CGRectMake(CGRectGetMaxX(noticeImg.frame) + 6.5, 12*ScaleY, 1, 20*ScaleY);
    [bgView.layer addSublayer:line];
    
    
    // 通知
    self.rollView = [[CHRollView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(line.frame) +6.5, 0, UIScreenW - CGRectGetMaxX(line.frame) - 6.5-44*ScaleX, 44 *ScaleY)];
    //点击公告内容
    __weak __typeof(self)weakSelf = self;
    self.rollView.clickBlock = ^(NSInteger index) {
        
        id obj = [LongriseRouter openURL:@"CHInformDetailController"];
        if(obj && [obj isKindOfClass:[UIViewController class]])
        {
            UIViewController *vc = obj;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
        
        //判断该类是否可以传参数
        if([LongriseRouter isImplLongriseRouterDelegaterWithObject:obj])
        {
            id<LongriseRouterDelegater> delegater = obj;
            if(delegater)
            {
                
                NSMutableDictionary *params = [NSMutableDictionary dictionary];
                params[@"model"] =  weakSelf.noticeArr[index];
                
                //进行传值，传入统一的block以供B进行回调
                [delegater setParams:params block:^(id obj) {
                    
                    
                }];
            }
        }
        
    };
    
    [bgView addSubview:self.rollView];
    
    UIButton *moreBtn = [[UIButton alloc] initWithFrame:CGRectMake(UIScreenW - 44*ScaleX, 0, 44*ScaleX, 44*ScaleY)];
    moreBtn.imageEdgeInsets = UIEdgeInsetsMake(15, 18, 15, 18);
    [moreBtn setImage:[UIImage imageNamed:@"right_arrow"] forState:UIControlStateNormal];
    [moreBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [moreBtn addTarget:self action:@selector(moreBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:moreBtn];
    
}


-(void)moreBtnClick{
    
    id obj = [LongriseRouter openURL:@"CHInformViewController"];
    if(obj && [obj isKindOfClass:[UIViewController class]])
    {
        UIViewController *vc = obj;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}


-(void)setupScrollView{
    
    NSArray *datas = [NSArray arrayWithObjects:@[@"22"], nil];
    self.scrollView = [[CHScrollView alloc] initWithFrame:CGRectMake(0, 0, UIScreenW  , 180 * ScaleY) withDatas:datas];
    [self.view addSubview:self.scrollView];
    
}

-(void)leftBarButtonItemClick{
    
    id obj = [LongriseRouter openURL:@"CHAccountViewController"];
    if(obj && [obj isKindOfClass:[UIViewController class]])
    {
        UIViewController *vc = obj;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}



#pragma mark - 获取网络数据
-(void)showStatisticsData{

    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = [Util getValue:@"areaid"];
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:(NSString *)[Util getValue:@"areaid"] encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    [[Globle getInstance].service requestWithServiceName:@"lcipappgovremind" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
      
        NSLog(@"统计数据%@",result);
        if ([result[@"code"] isEqualToString:@"1"]) {
            
            NSDictionary *dict = result[@"data"];
            NSString *repairnum = [NSString stringWithFormat:@"维修车辆（%@）",dict[@"repairnum"]];
            NSString *recordnum = [NSString stringWithFormat:@"维修记录（%@）",dict[@"recordnum"]];
            NSString *parts = [NSString stringWithFormat:@"配件（%@）",dict[@"parts"]];
            NSString *evaluatenum = [NSString stringWithFormat:@"评价（%@）",dict[@"evaluatenum"]];
            
            NSString *complaint = [NSString stringWithFormat:@"投诉（%@）",dict[@"complaint"]];
            NSString *comnum = [NSString stringWithFormat:@"已注册企业（%@）",dict[@"comnum"]];
            NSString *recordnu = [NSString stringWithFormat:@"已对接企业（%@）",dict[@"dockcomnum"]];
            NSString *uploadnum = [NSString stringWithFormat:@"已上传企业（%@）",dict[@"uploadnum"]];
            self.noticeTitles = [NSArray arrayWithObjects:repairnum,recordnum,parts,evaluatenum,complaint,comnum,recordnu,uploadnum, nil];
            
             dispatch_semaphore_signal(_semaphore);
   
        }
        
    }];
}


//   获取最近统计数据
-(void)getRecentStatisticsDataWithDays:(int)days{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = [Util getValue:@"areaid"];
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:(NSString *)[Util getValue:@"areaid"] encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"start"] =self.startTime;
    params[@"end"] = self.endTime;
    [[Globle getInstance].service requestWithServiceName:@"lcipappgovtotle" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
      dispatch_semaphore_signal(_semaphore);
        NSLog(@"%@",result);
        
        if ([result[@"code"] isEqualToString:@"1"]) {
            NSDictionary *dict = result[@"data"];
            self.resultArr = @[dict[@"repairnum"],dict[@"recordnum"],dict[@"comnum"],dict[@"parts"] ,dict[@"evaluatenum"],dict[@"complaint"]];

        }
        
         [self.collectionView reloadData];
    }];
    
}


-(void)getNoticeData{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = [Util getValue:@"areaid"];
    params[@"userflag"] = [Util getValue:@"userflag"];
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:(NSString *)[Util getValue:@"areaid"] encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"pagesize"] = @"50";
    params[@"pagenum"] = @"1";
    params[@"type"] = @"3";
    [[Globle getInstance].service requestWithServiceName:@"lcipappgovnewslist" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
        [self.datas removeAllObjects];
          dispatch_semaphore_signal(_semaphore);
        if ([result[@"code"] isEqualToString:@"1"]) {
            
            for (NSDictionary *dict in result[@"data"][@"list"]) {
                CHNoticeModel *model = [CHNoticeModel objectWithKeyValues:dict];
                [self.noticeArr addObject:model];
                
                [self.datas addObject:dict[@"title"]];
            }
            
        }
    }];
}

//  获取下级区域
-(void)getLevelAreaData{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = [Util getValue:@"areaid"];
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:(NSString *)[Util getValue:@"areaid"] encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    [[Globle getInstance].service requestWithServiceName:@"lcipappgovarealist" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
          dispatch_semaphore_signal(_semaphore);
        if ([result[@"code"] isEqualToString:@"1"]) {
            NSMutableArray *tempArr = [NSMutableArray array];
            NSMutableArray *areacns = [NSMutableArray array];
            for (NSDictionary *dict in result[@"data"][@"arealist"]) {
                PJ_Model *model = [PJ_Model objectWithKeyValues:dict];
                [tempArr addObject:model];
                [areacns addObject:dict[@"areacn"]];
            }
            [Globle getInstance].datas = tempArr;
             [Globle getInstance].areacns = areacns;
        }
        
    }];
    
    
    
}



//  获取从开始到当前的时间天数
-(int)getDays{
    
    
    //首先创建格式化对象
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    //然后创建日期对象
    
   NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
   [formatter setDateFormat:@"yyyy"];
   NSInteger currentYear = [[formatter stringFromDate:date] integerValue];
    
    NSDate *date1 = [dateFormatter dateFromString:[NSString stringWithFormat:@"%ld-01-01 00:00:00",currentYear]];
    

    
    //计算时间间隔（单位是秒）
    
    NSTimeInterval time = [date timeIntervalSinceDate:date1];
    
    //计算天数
    
    int days = ((int)time)/(3600*24);
    
    return days;
}


-(void)getAdvertList:(void(^)())finish{
    //网络请求..成功后调用一下finish,失败也调用finish
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = [Util getValue:@"areaid"];
    params[@"userflag"] = [Util getValue:@"userflag"];
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:(NSString *)[Util getValue:@"areaid"] encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"pagesize"] = @"50";
    params[@"pagenum"] = @"1";
    params[@"type"] = @"3";
    [[Globle getInstance].service requestWithServiceName:@"lcipappgovnewslist" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
        [self.datas removeAllObjects];
        
        
        if ([result[@"code"] isEqualToString:@"1"]) {
            
            finish();
            
            for (NSDictionary *dict in result[@"data"][@"list"]) {
                CHNoticeModel *model = [CHNoticeModel objectWithKeyValues:dict];
                [self.noticeArr addObject:model];
                
                [self.datas addObject:dict[@"title"]];
            }
            self.rollView.dataArr = self.datas;
        }
    }];
    
    
}




- (void)getNetworkingData{
    
    [MBProgressHUD showMessage:@"加载中..."];
    
    // 创建信号量
   _semaphore = dispatch_semaphore_create(0);
    
    // 创建全局并行
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, queue, ^{
        
        // 获取通知数据
        [self getNoticeData];
        
         dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
        
    });
    NSString *usertype = (NSString *)[Util getValue:@"usertype"];
    
    if ([usertype isEqualToString:@"1"] ) {
        dispatch_group_async(group, queue, ^{
            // 获取统计数据
            [self showStatisticsData];
            dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
            
           
        });
        
    }
    dispatch_group_async(group, queue, ^{
        
        
        // 获取下级区域
        [self getLevelAreaData];
        
          dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
        
        
    });
    
    dispatch_group_async(group, queue, ^{
        
        // 获取最近统计数据
        [self getRecentStatisticsDataWithDays:7];
        
          dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
       
    });
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{       //   刷新UI
        
          NSLog(@"三次都执行完了");
        
        [MBProgressHUD hideHUD];

        self.rollView.dataArr = self.datas;
        
       
        NSString *cityStr = [Globle getInstance].userInfoDic[@"areacn"];
        NSString *title = [NSString stringWithFormat:@"昨日统计（%@）",cityStr];
        [SelectAlert showWithTitle:title titles:self.noticeTitles];
        

    });
    
  
    
    
}




//   查询统计
-(void)selectBtnClick{
    
    self.popView = [CHPopView popView];
    self.popView.delegate = self;
    [self.popView show];
}

-(void)didClickBtnWithTitle:(NSString *)title andIndex:(NSInteger)index{
    
    int num = 0;
    if (index == 0) {
        num = 7;
        
    }else if(index == 1){
        num = 30;
        
    }else{
        
        num = [self getDays];
        
    }
    self.startTime = [Util getStartTimeWithNumber:num];
    [MBProgressHUD showMessage:@"加载数据中···"];
    
    [self.signLabel setText:title];
    
    [self getRecentStatisticsDataWithDays:num];
    [MBProgressHUD hideHUD];
    [self.popView dismiss];
}









#pragma mark - UICollectionViewDataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.titles.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID = @"homeCell";
    CHHomeViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    cell.imgName = [NSString stringWithFormat:@"home_icon_%zd",indexPath.row+1];
    cell.titleName = self.titles[indexPath.row];
    cell.numLabel.text = self.resultArr[indexPath.row];
    return cell;
}

#pragma mark--UICollectionViewDelegateFlowLayout
////定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0,0);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}
// 两行之间的最小间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 4) {
            
            id obj = [LongriseRouter openURL:@"CHComplainCountController"];
            if(obj && [obj isKindOfClass:[UIViewController class]])
            {
                UIViewController *vc = obj;
                [self.navigationController pushViewController:vc animated:YES];
            }
            
            //判断该类是否可以传参数
            if([LongriseRouter isImplLongriseRouterDelegaterWithObject:obj])
            {
                id<LongriseRouterDelegater> delegater = obj;
                if(delegater)
                {
                    
                    NSMutableDictionary *params = [NSMutableDictionary dictionary];
                    params[@"title"] = @"评价统计";
                    params[@"starttime"] = self.startTime;
                    params[@"endtime"] = self.endTime;
                    params[@"areacn"] = (NSString *)[Util getValue:@"areacn"];
                    //进行传值，传入统一的block以供B进行回调
                    [delegater setParams:params block:^(id obj) {
                        
                        
                    }];
                }
            }
            
        }else if (indexPath.row == 5){
            
            id obj = [LongriseRouter openURL:@"CHComplainCountController"];
            if(obj && [obj isKindOfClass:[UIViewController class]])
            {
                UIViewController *vc = obj;
                [self.navigationController pushViewController:vc animated:YES];
            }
            
            //判断该类是否可以传参数
            if([LongriseRouter isImplLongriseRouterDelegaterWithObject:obj])
            {
                id<LongriseRouterDelegater> delegater = obj;
                if(delegater)
                {
                    
                    NSMutableDictionary *params = [NSMutableDictionary dictionary];
                    params[@"title"] = @"投诉统计";
                    params[@"starttime"] = self.startTime;
                    params[@"endtime"] = self.endTime;
                    params[@"areacn"] = (NSString *)[Util getValue:@"areacn"];
                    //进行传值，传入统一的block以供B进行回调
                    [delegater setParams:params block:^(id obj) {
                        
                        
                    }];
                }
            }
            
        }else if (indexPath.row == 2){
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeToWXQY" object:nil];
            UINavigationController *nav = [self.tabBarController.viewControllers objectAtIndex:3];
            UIViewController *vc = nav.topViewController;
            
            if ([vc isKindOfClass:[CHQueryViewController class]]) {
                [((CHQueryViewController *)vc) setMark:1];
            }
            self.tabBarController.selectedIndex = 3;
            
        }else if(indexPath.row == 1){
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeToWXJL" object:nil];
            UINavigationController *nav = [self.tabBarController.viewControllers objectAtIndex:3];
            UIViewController *vc = nav.topViewController;
            
            if ([vc isKindOfClass:[CHQueryViewController class]]) {
                [((CHQueryViewController *)vc) setMark:2];
            }
            self.tabBarController.selectedIndex = 3;
            
            
        }else{
            
            [MBProgressHUD showWarning:@"敬请期待"];
       
        }
    }
    
    
    
}




#pragma mark 检查版本
-(void)checkVersion
{
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setValue:leapAPPname forKey:@"appname"];
    
    [[Globle getInstance].service RequestWithServiceName:@"lbcp_getAppVersion" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
        
        NSLog(@"%@",result);
        NSDictionary *dic = (NSDictionary *)result;
        if(nil != dic)
        {
            [MBProgressHUD hideHUD];
            //获取本地版本
            self.remarksPath = dic[@"remarks"];
            NSString *localVersion = VersionCode;
            int localVersionNUm = (localVersion == nil ? -1 : [localVersion intValue]);
            //获取服务器版本
            NSString *serverVersion = [dic valueForKey:@"appversion"];
            int serverVersionNum = (serverVersion == nil ? -1 : [serverVersion intValue]);
            //判断是非升级
            if(localVersionNUm < serverVersionNum)
            {
                NSString *upgrade = [dic valueForKey:@"upgrade"];
                if([@"1" isEqualToString:upgrade])    //   强制升级
                {
                    self.alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"有新的版本，请及时更新。" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                }
                else
                {
                    self.alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"有新的版本，请及时更新。" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",@"取消", nil];
                }
                
                [self.alertView show];
                
            }
        }
    }];
    
}

#pragma mark - UIAlertView delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView == self.alertView)
    {
        if(buttonIndex == 0)
        {
            NSString *urlStr = [NSString stringWithFormat:@"%@",self.remarksPath];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
        }
    }
}




- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.rollView start];
//    //设置导航栏背景图片为一个空的image，这样就透明了
//    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
//
//    //去掉透明后导航栏下边的黑边
//    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNoticeData) name:@"sendSuccessMessage" object:nil];
    
    
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.rollView stopTimer];
    
    
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    
//    UIImage *image = [UIImage imageNamed:@"search"];
//    UIImage *newImage = [image stretchableImageWithLeftCapWidth:0.5 topCapHeight:0.5];
//    //    如果不想让其他页面的导航栏变为透明 需要重置
//    [self.navigationController.navigationBar setBackgroundImage:newImage forBarMetrics:UIBarMetricsDefault];
//    [self.navigationController.navigationBar setShadowImage:nil];
    
    
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    
    return UIStatusBarStyleLightContent;
    
}


-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"主页销毁了");
}


@end
